package com.huluobo.a2203kotlinjetpackdemo.coroutine

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.huluobo.a2203kotlinjetpackdemo.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.Dispatcher
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create

class RetrofitActivity : AppCompatActivity() {
    //RetrofitManager
    private val retrofit = Retrofit.Builder().baseUrl("http://10.161.9.80:7012")
        .addConverterFactory(GsonConverterFactory.create()).build()

    //BaseRepo
    private val apiService = retrofit.create(ApiService::class.java)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_retrofit)

        //发起请求
        apiService.loadBanner().enqueue(object : Callback<BannerBeanResult> {
            override fun onResponse(call: Call<BannerBeanResult>, response: Response<BannerBeanResult>) {
                val gson = Gson().toJson(response.body())
                val textView = findViewById<TextView>(R.id.retrofit_tv)
                textView.text = gson
            }

            override fun onFailure(call: Call<BannerBeanResult>, t: Throwable) {
                Log.i("TagA", "t:${t.message}")
            }
        })

        val job = Job()
        //retrofit2.8一下,不支持直接在main调用协程,需要协程切换
//        CoroutineScope(job).launch(Dispatchers.Main) {
//            val result = withContext(Dispatchers.IO) {
//                apiService.loadBanner2()
//            }
//            val gson = Gson().toJson(result)
//            val textView = findViewById<TextView>(R.id.retrofit_tv)
//            textView.text = gson
//        }

        //retrofit2.9可以直接在main线程中调用协程来进行线程切换
        CoroutineScope(job).launch(Dispatchers.Main) {
            val result = apiService.loadBanner2()
            val textView = findViewById<TextView>(R.id.retrofit_tv)
            textView.text = Gson().toJson(result)
        }

        lifecycleScope.launchWhenCreated {
            Log.i("TagA", "onCreate")
        }

        lifecycleScope.launchWhenResumed {
            Log.i("TagA", "onResume")
        }

        lifecycleScope.launchWhenStarted {
            Log.i("TagA", "onStart")
        }
    }
}